//
//  YImageLoader.swift
//  EasyEverything
//
//  Created by YangZhe on 17/3/15.
//  Copyright © 2017年 kuletech. All rights reserved.
//

import UIKit

open class YImageLoader {
    
    let cache = NSCache<NSString, AnyObject>()
    
    public class var sharedLoader : YImageLoader {
        struct Static {
            static let instance : YImageLoader = YImageLoader()
        }
        return Static.instance
    }
    
    public func imageForUrl(urlString: String, completionHandler: @escaping (_ image: UIImage?, _ url: String) -> ()) {
        
        if TextUtils.isEmpty(urlString){
            return
        }
        
        DispatchQueue.global(qos: .background).async {
            if let goodData = self.cache.object(forKey: urlString as NSString) as? NSData {
                let image = UIImage(data: goodData as Data)
                DispatchQueue.main.async {
                    completionHandler(image, urlString)
                }
                return
            }
            
            URLSession.shared.dataTask(with: URLRequest(url: URL(string: urlString)!)) { data, response, error in
                if (error != nil) {
                    DispatchQueue.main.async {
                        completionHandler(nil, urlString)
                    }
                    return
                }
                
                if let data = data{
                    if let image = UIImage(data: data){
                        self.cache.setObject(data as AnyObject, forKey: urlString as NSString)
                        DispatchQueue.main.async {
                            completionHandler(image, urlString)
                        }
                    }else{
                        DispatchQueue.main.async {
                            completionHandler(nil, urlString)
                        }
                    }
                }else {
                    DispatchQueue.main.async {
                        completionHandler(nil, urlString)
                    }
                }
            }.resume()
        }
    }
}
